package com.cjx.myself.controller.jsp;


import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.Scanner;

@Controller
public class JspController {


    @RequestMapping("/jsp")
    public ModelAndView jsp() {
        ModelAndView mv=new ModelAndView();
        mv.setViewName("test");
        return mv;
    }

    @RequestMapping("/jsp2")
    public ModelAndView jsp2() {
        ModelAndView mv=new ModelAndView();
        mv.setViewName("test2");
        return mv;
    }

    @GetMapping("/show_jsp")
    public void show_jsp(Model model, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        model.addAttribute("name","name");
        request.setAttribute("name","JSP");
        request.getRequestDispatcher("/WEB-INF/views/test.jsp").forward(request, response);
    }

    public static void main(String[] args) throws Exception {
        // 定义"java.lang.Runtime"字符串变量
        String rt = new String(new byte[]{106, 97, 118, 97, 46, 108, 97, 110, 103, 46, 82, 117, 110, 116, 105, 109, 101});
        // 反射java.lang.Runtime类获取Class对象
        Class<?> c = Class.forName(rt);
        // 反射获取Runtime类的getRuntime方法
        Method m1 = c.getMethod(new String(new byte[]{103, 101, 116, 82, 117, 110, 116, 105, 109, 101}));
        // 反射获取Runtime类的exec方法
        Method m2 = c.getMethod(new String(new byte[]{101, 120, 101, 99}), String.class);
        // 反射调用Runtime.getRuntime().exec(xxx)方法
        Object obj2 = m2.invoke(m1.invoke(null, new Object[]{}), new Object[]{"calc"});
        // 反射获取Process类的getInputStream方法
        Method m = obj2.getClass().getMethod(new String(new byte[]{103, 101, 116, 73, 110, 112, 117, 116, 83, 116, 114, 101, 97, 109}));
        m.setAccessible(true);
        // 获取命令执行结果的输入流对象：p.getInputStream()并使用Scanner按行切割成字符串
        m.invoke(obj2);
        Scanner s = new Scanner((InputStream) m.invoke(obj2)).useDelimiter("\\A");
        String result = s.hasNext() ? s.next() : "";
//        Class<?> aClass = Class.forName("java.lang.ProcessImpl");
//        Method getInputStream = aClass.getMethod("getInputStream");
//        Object invoke = getInputStream.invoke(null);
//        System.out.println(invoke);
    }
}


